package com.briup.estore.service.impl;

import com.briup.estore.bean.OrderForm;
import com.briup.estore.bean.OrderFormExample;
import com.briup.estore.bean.OrderLine;
import com.briup.estore.bean.OrderLineExample;
import com.briup.estore.dao.OrderFormMapper;
import com.briup.estore.dao.OrderLineMapper;
import com.briup.estore.service.OrderService;
import com.briup.estore.util.MyBatisSqlSessionFactory;
import com.briup.estore.vm.BookVM1;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class OrderServiceImpl implements OrderService {
    private OrderFormMapper orderFormMapper;
    private OrderLineMapper orderLineMapper;

    {
        SqlSession sqlSession = MyBatisSqlSessionFactory.openSession();
        orderFormMapper = sqlSession.getMapper(OrderFormMapper.class);
        orderLineMapper = sqlSession.getMapper(OrderLineMapper.class);
    }

    @Override
    public Integer addOrderForm(OrderForm orderForm) {
        orderFormMapper.insert(orderForm);
        return orderForm.getId();
    }

    @Override
    public Integer addOrderLine(Integer orderFormId, List<BookVM1> list) {
        OrderLine orderLine = new OrderLine();
        for (BookVM1 b : list) {
            orderLine.setNum(b.getNum());
            orderLine.setBookId(b.getId());
            orderLine.setCost(b.getTotal());
            orderLine.setOrderformId(orderFormId);
            orderLineMapper.insert(orderLine);
        }
        return list.size();
    }

    @Override
    public List<OrderForm> findAllOrderForm(Integer userId) {
        OrderFormExample example = new OrderFormExample();
        example.createCriteria().andCustomerIdEqualTo(userId);
        return orderFormMapper.selectByExample(example);
    }

    @Override
    public List<OrderLine> findAllOrderLine(Integer formId) {
        OrderLineExample example = new OrderLineExample();
        example.createCriteria().andOrderformIdEqualTo(formId);
        return orderLineMapper.selectByExample(example);
    }

    @Override
    public void removeOrderFormById(Integer formId) {
        orderFormMapper.selectByPrimaryKey(formId);
    }
}
